package com.xju.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.xju.entity.College;

import static com.xju.util.DBUtil.getConnection;

public class CollegeDaoImpl implements CollegeDao {
    @Override
    public List<College> findAllColleges() {
        String sql = "SELECT * FROM college ORDER BY college_name";
        List<College> colleges = new ArrayList<>();

        try (Connection conn = getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql);
                ResultSet rs = pstmt.executeQuery()) {

            while (rs.next()) {
                College college = new College();
                college.setCollegeId(rs.getInt("college_id"));
                college.setCollegeName(rs.getString("college_name"));
                college.setDescription(rs.getString("description"));
                colleges.add(college);
            }
        } catch (SQLException e) {
            throw new DataAccessException("查询所有学院失败", e);
        }

        return colleges;
    }

    @Override
    public List<College> findCollegesByName(String name) {
        String sql = "SELECT * FROM college WHERE college_name LIKE ? ORDER BY college_name";
        List<College> colleges = new ArrayList<>();

        try (Connection conn = getConnection();
                PreparedStatement pstmt = conn.prepareStatement(sql)) {

            pstmt.setString(1, "%" + name + "%");
            ResultSet rs = pstmt.executeQuery();

            while (rs.next()) {
                College college = new College();
                college.setCollegeId(rs.getInt("college_id"));
                college.setCollegeName(rs.getString("college_name"));
                college.setDescription(rs.getString("description"));
                colleges.add(college);
            }
        } catch (SQLException e) {
            throw new DataAccessException("根据名称查询学院失败", e);
        }

        return colleges;
    }
}